import { clearToken } from "@/utils/auth";
import { useUserStore } from "@/store";

let erroring = false;

export default {
  responseResolve(response) {
    if (!response) return Promise.reject(new Error("no response"));
    const { data, status, config } = response;
    // 处理stream数据
    if (["arraybuffer", "blob", "stream"].includes(config?.responseType))
      return response;

    // oss上传接口处理
    if (config.url.indexOf("oss-cn") !== -1) {
      return status;
    }

    if (status !== 200) {
      return Promise.reject(new Error("request error"));
    }

    if (data && data.code !== 200) {
      if (data.code === 401) {
        const userStore = useUserStore();
        userStore.logout();
        data.msg = "登录失效，请重新登录";
        setTimeout(() => {
          userStore.goLogin();
        }, 1000);
      }
      ElMessage({
        message: data.msg,
        type: "error",
        duration: 2000,
      });
      return Promise.reject(new Error(data.msg));
    }
    return data;
  },
  responseError(error) {
    if (erroring) return;
    erroring = true;
    ElMessage({
      message: error.message,
      type: "error",
      duration: 3000,
    });
    setTimeout(() => {
      erroring = false;
    }, 3000);
  },
};
